package com.LinkBlockQueue;


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

//线程池下操作 阻塞队列
//日常开发中使用较多的 数组阻塞队列  ArrayBlockingQueue
//队列1 抛出异常

public class BlockingQueueDemo {
    public static void main(String[] args) {
//        test1();
        try {
//            test2();
            test3();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    public static void test1(){
        //队列大小
        ArrayBlockingQueue queue = new ArrayBlockingQueue(4);

        /**
         * 抛出异常  add remove
         * 调用add方法来添加元素，添加成功时会返回true，
         * 添加元素个数大于队列长度时，会抛出Queue full的异常，表明队列已满，无法继续添加元素
         * */
        System.out.println(queue.add("a"));
        System.out.println(queue.add("b"));
        System.out.println(queue.add("c"));
        System.out.println(queue.add("d"));

        //当移除元素个数大于队列中元素个数时，会抛出异常。
        System.out.println(queue.remove());
        System.out.println(queue.remove());
        System.out.println(queue.remove());
        System.out.println(queue.remove());
    }
    public static void test2() throws InterruptedException {
        /**
         * 阻塞线程  put take
         * */
        ArrayBlockingQueue queue2 = new ArrayBlockingQueue(4);
        queue2.put("a");
        queue2.put("b");
        queue2.put("c");
        queue2.put("d");
//        queue2.put("d");
        System.out.println(queue2.take());
        System.out.println(queue2.take());
        System.out.println(queue2.take());
        System.out.println(queue2.take());
        System.out.println(queue2.take());

    }
    public static void test3() throws InterruptedException {
        /**
         * 有返回值的队列 offer  poll
         * */
        ArrayBlockingQueue queue3 = new ArrayBlockingQueue(4);
//        System.out.println(queue3.offer("a"));
//        System.out.println(queue3.offer("a"));
//        System.out.println(queue3.offer("a"));
//
//        System.out.println(queue3.poll());
//        System.out.println(queue3.poll());
//        System.out.println(queue3.poll());

        /**
         *  超时返回 offer poll 带时间参数
         *  指定时间内未能存入或取出元素时 offer - false , poll - null
         * */
        System.out.println(queue3.offer("a", 1, TimeUnit.SECONDS));
        System.out.println(queue3.offer("b", 4, TimeUnit.SECONDS));
        System.out.println(queue3.offer("c", 1, TimeUnit.SECONDS));

        System.out.println(queue3.poll(2, TimeUnit.SECONDS));
        System.out.println(queue3.poll(2, TimeUnit.SECONDS));
        System.out.println(queue3.poll(2, TimeUnit.SECONDS));
        System.out.println(queue3.poll(2, TimeUnit.SECONDS));//这个就是null


    }
}
